#include "World.h"
#include "Camera.h"
#include "base.h"
#include "Utils.h"
#include "ScrGame.h"
#include "BufferedRandom3D.h"
World::World(void)
{
	m_pBlockLibrary = NULL;
	m_pBlockRenderer = NULL;
	m_pRenderer = NULL;
	m_pOwnerScreen = NULL;
}
World::~World(void)
{
}
int World::Initialize(IGameScreen *pOwner, BlockLibrary *pBlockLibrary,
	BlockRenderer *pBlockRenderer, uint terrainTexture)
{
	m_pBlockLibrary = pBlockLibrary;
	m_pBlockRenderer = pBlockRenderer;
	m_pOwnerScreen = pOwner;
	m_pRenderer = m_pOwnerScreen->GetRenderer();

	m_nTerrainTexture = terrainTexture;

	m_chunkManager.Initialize(&m_playerEntity, 1);
	m_chunkManager.Update();

	return 0;
}
void World::Draw()
{	
	//Check terrain visibility
	m_chunkManager.

	//DrawTerrainGrid(vector2(0,0), 5.0f, 128);
}
void World::Update()
{
	m_chunkManager.Update();
}
int World::Generate(int seed)
{
	m_nSeed = seed;
	//m_terrainGenerator.Seed(seed, 0.25f);
	BufferedRandom3D rndMap(128,1,128,16,54647463);

	float *pRndBlock = rndMap.GetBlock(0,0);
	float stepCount = 128;
	float step = 1.0f;
	m_pTMap = new float[stepCount*stepCount];
	for(int z = 0; z < stepCount; z++)
	{
		float zStep = step*z;
		for(int x = 0; x < stepCount; x++)
		{
			float xStep = step*x;
			m_pTMap[MAP_INDEX(x,z)] = pRndBlock[x+z*128] * 64;
		}
	}
	return 0;
}
void World::DrawTerrainGrid(vector2 start, float step, int stepCount)
{
	m_pRenderer->SetColor(color::Purple * 0.6f);
	m_pRenderer->BeginUniformLine(5.0f);
	for(int z = 0; z < stepCount; z++)
	{
		float zStep = start.y + step*z;
		for(int x = 0; x < stepCount; x++)
		{
			float xStep = start.x + step*x;
			vector3 thisPoint(xStep, m_pTMap[MAP_INDEX(x,z)], zStep);
			if(x < stepCount-1)
			{
				vector3 nextX(xStep+step, m_pTMap[MAP_INDEX(x+1,z)], zStep);
				m_pRenderer->DrawUniformLine(thisPoint, nextX);
			}
			if(z < stepCount-1)
			{
				vector3 nextZ(xStep, m_pTMap[MAP_INDEX(x,z+1)], zStep+step);
				m_pRenderer->DrawUniformLine(thisPoint, nextZ);
			}
		}
	}
	m_pRenderer->EndUniformLine();
}